#include "blockqueue.hpp"
#include "task.hpp"
#include <unistd.h>
template <class C, class S>
class blockqueues
{
public:
    blockqueue<C> *c_bq;
    blockqueue<S> *s_bq;
};

// 生产者
void *producer(void *arg)
{
    blockqueues<calcTask, saveTask> *bqs = static_cast<blockqueues<calcTask, saveTask> *>(arg);
    string ops = "+-*/%";
    while (true)
    {
        sleep(5);
        int x = rand() % 100;
        int y = rand() % 10;
        char op = ops[rand() % 5];
        calcTask task(x, y, op);
        bqs->c_bq->push(task);
        cout << "推送任务成功" << endl;
    }
    return nullptr;
}

// 消费者
void *consumer(void *arg)
{
    blockqueues<calcTask, saveTask> *bqs = static_cast<blockqueues<calcTask, saveTask> *>(arg);
    while (true)
    {
        calcTask ctask;
        bqs->c_bq->pop(&ctask);
        cout << "计算任务成功" << endl;
        saveTask stask(ctask());
        bqs->s_bq->push(stask);
    }
    return nullptr;
}
void *saver(void *arg)
{
    blockqueues<calcTask, saveTask> *bqs = static_cast<blockqueues<calcTask, saveTask> *>(arg);
    while (true)
    {
        saveTask stask;
        bqs->s_bq->pop(&stask);
        stask();
        cout << "保存任务成功" << endl;
    }
    return nullptr;
}
int main()
{
    pthread_t t1, t2, t3;
    blockqueues<calcTask, saveTask> bqs;
    bqs.c_bq = new blockqueue<calcTask>(5);
    bqs.s_bq = new blockqueue<saveTask>(5);
    srand(time(nullptr));
    pthread_create(&t1, nullptr, producer, (void *)&bqs);
    pthread_create(&t2, nullptr, consumer, (void *)&bqs);
    pthread_create(&t3, nullptr, saver, (void *)&bqs);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    return 0;
}